package tech.waterism.utils;


import tech.waterism.dto.CurveZVDto;
import tech.waterism.dto.FPIndexDto;
import tech.waterism.entity.FCurveHs;

import java.util.Comparator;
import java.util.List;

public class ConvertZV {
    /**
     * 已知水位，用三点插值求库容
     *
     * @return 库容
     * @parameter double v
     */
    public static CurveZVDto getVFromZ(List<FCurveHs> curveHs, double z) {
        CurveZVDto result = new CurveZVDto();
        double v;
        v = MathFun.insert2(z, curveHs.stream().mapToDouble(FCurveHs::getZ).toArray(),
                curveHs.stream().mapToDouble(FCurveHs::getS).toArray(), curveHs.size());
        //        v = v * 1000000L;
        result.setResult(v);
        result.setMsg(checkVZ(curveHs, z));
        return result;
    }

    private static String checkVZ(List<FCurveHs> curveHs, double z) {
        if (curveHs.size() == 0) {
            return "无水位库容曲线";
        }
        if (z > curveHs.stream().max(Comparator.comparing(FCurveHs::getZ)).get().getZ() ||
                z < curveHs.stream().min(Comparator.comparing(FCurveHs::getZ)).get().getZ()) {
            return "超水位库容曲线上下限";
        }
        return null;
    }

    /**
     * 已知库容，用三点插值求水位
     *
     * @return 水位
     * @parameter double v
     */
    public static CurveZVDto getZFromV(List<FCurveHs> curveHs, double v) {
        CurveZVDto result = new CurveZVDto();
        double z;
        //        v = v / 1000000L;
        z = MathFun.insert2(v, curveHs.stream().mapToDouble(FCurveHs::getS).toArray(),
                curveHs.stream().mapToDouble(FCurveHs::getZ).toArray(), curveHs.size());
        result.setResult(z);
        result.setMsg(checkZV(curveHs, v));
        return result;
    }

    private static String checkZV(List<FCurveHs> curveHs, double v) {
        if (curveHs.size() == 0) {
            return "无水位库容曲线";
        }
        if (v > curveHs.stream().max(Comparator.comparing(FCurveHs::getS)).get().getS() ||
                v < curveHs.stream().min(Comparator.comparing(FCurveHs::getS)).get().getS()) {
            return "超水位库容曲线上下限";
        }
        return null;
    }

    public static void setErrMsgCurveHs(FPIndexDto fpIndex, String msg) {
        if (msg != null) {
            fpIndex.setErrMsgCurveHs(msg);
        }
    }
}
